import { useState, useEffect, useRef, useCallback } from 'react';
import './index.less';
import RankingList from '@/pages/RankingList';
import DialogueList from '@/pages/DialogueList';
import { IconCaretRight } from '@arco-design/web-react/icon';
import Report from '@/pages/Report';
import Pass from '@/assets/AiImgs/Pass.png';
import NoPass from '@/assets/AiImgs/noPass.png';
import tabchecked from '@/assets/AiImgs/tabchecked.png';
import { Link } from 'react-router-dom';
import { getTrainPracticeMain, getTrainReport } from '@/api/train';
import { useSearchParams } from 'react-router-dom';
import TrainingLink from '@/components/TrainingLink';

export default function PracticeDetail() {
    const [currentPage, setCurrentPage] = useState<number>(0);
    const [searchParams] = useSearchParams();
    const picid = searchParams.get('prcid');
    const [pageDetail, setPageDetail] = useState<any>({});
    const [isWrap, setIsWrap] = useState(false);
    const [loading, setLoading] = useState(true); // 添加加载状态
    const [error, setError] = useState(false);   // 添加错误状态
    const titleEleRef = useRef<any>({});
    
    const fetchData = useCallback(async () => {
        try {
            setLoading(true);
            setError(false);
            
            if (!picid) {
                throw new Error('缺少训练ID');
            }
            
            const res = await getTrainPracticeMain(picid);
            if (res.code === 2000) {
                // 确保设置空对象而不是undefined
                setPageDetail(res.data?.summary || {}); 
            } else {
                throw new Error('数据获取失败');
            }
        } catch (err) {
            console.error('获取训练数据失败:', err);
            setError(true);
            setPageDetail({});
        } finally {
            setLoading(false);
        }
    }, [picid]);
    
    useEffect(() => {
        fetchData();
    }, [fetchData]);
    
    useEffect(() => {
        // 确保在组件挂载后再计算高度
        if (titleEleRef.current) {
            let titleH = titleEleRef.current.offsetHeight || 0;
            setIsWrap(titleH > 32);
        }
    }, [pageDetail]);

    // 处理子组件通知 - 使用useCallback确保引用稳定
    const handleChildNotification = useCallback((data: { message: string }) => {
        console.log("收到子组件通知:", data);
        
        // 当收到通知时，重新获取数据
        fetchData();
    }, [fetchData]);

    return (
        <div className="practiceDetail"  >
            <div className="text-[#222222]">
                <div className=" pb-5 pl-5 py-2.5 pr-[22px] BGImg">
                    <div className='flex justify-between items-end'>
                        <div className='grow w-[0]'>
                            <div className="mb-2.5 text-2xl font-semibold" ref={titleEleRef}>
                                {pageDetail?.title || ''}
                            </div>
                            <div className="flex font-light mb-[5px] items-center">
                                第&nbsp;
                                <div className={`text-lg yellowdown ${pageDetail?.training_times > 9 ? 'yellowdown_auto' : ''} font-black`} style={{ fontFamily: 'SpeedeeApp-BoldItalic' }}>
                                    <span className="relative z-50">{pageDetail?.training_times || 0}</span>
                                </div>
                                &nbsp;次陪练&nbsp;
                                <div className="text-lg yellowdown font-black" style={{ fontFamily: 'SpeedeeApp-BoldItalic' }}>
                                    <span className="relative z-50">{pageDetail?.duration || 0}</span>
                                </div>
                                &nbsp;分钟&nbsp;｜&nbsp;
                                <TrainingLink trainingid={pageDetail?.training_id} title={pageDetail?.title || ''}/>
                            </div>
                            <div className="font-light">训练时间：{pageDetail?.training_at || '未知时间'}</div>
                        </div>
                        {pageDetail?.training_result !== undefined && (
                            <div className='w-[67px]'>
                                <img 
                                    className='w-[67px]' 
                                    src={pageDetail?.training_result === 1 ? Pass : NoPass} 
                                    alt={pageDetail?.training_result === 1 ? '通过' : '未通过'}
                                />
                            </div>
                        )}
                    </div>
                </div>
                <div className="">
                    <div style={{ marginTop: isWrap ? '-132px' : '-164px' }} className={`grid grid-cols-3 rounded-t-2xl ${currentPage === 0 ? 'checkedbg1' : currentPage === 1 ? 'checkedbg2' : 'checkedbg3'}`}>
                        <div className={`relative pt-[15px] pb-[8px] text-center  ${currentPage === 0 ? 'bg-white font-bold text-lg rounded-t-2xl' : 'text-base'}`} onClick={() => setCurrentPage(0)}>
                            练习报告
                            {currentPage === 0 && <img src={tabchecked} className='w-[14px] inline absolute top-3' alt="选中标记" />}
                        </div>
                        <div className={` relative  pt-[15px] pb-[8px] text-center ${currentPage === 1 ? 'bg-white font-bold text-lg rounded-t-2xl' : 'text-base'}`} onClick={() => setCurrentPage(1)}>
                            对话详情
                            {currentPage === 1 && <img src={tabchecked} className='w-[14px] inline absolute top-3' alt="选中标记" />}
                        </div>
                        <div className={` relative  pt-[15px] pb-[8px] text-center ${currentPage === 2 ? 'bg-white font-bold text-lg rounded-t-2xl' : 'text-base'}`} onClick={() => setCurrentPage(2)}>
                            排行榜
                            {currentPage === 2 && <img src={tabchecked} className='w-[14px] inline absolute top-3' alt="选中标记" />}
                        </div>
                    </div>
                    <div className='bg-[#f2f2f2]' style={{ marginTop: '-0.8px' }}>
                        {currentPage === 0 && <Report reportResult={pageDetail?.is_main_score} onNotify={handleChildNotification}/>}
                        {currentPage === 1 && <DialogueList />}
                        {currentPage === 2 && <RankingList pageDetail={pageDetail} />}
                    </div>
                </div>
            </div>
        </div>
    );
}